home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5906 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: pegasus.montclair.edu!harmon
  2. From: harmon@pegasus.montclair.edu (Derek Harmon)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How do I round and truncate floats to integers?
  5. Date: 16 Feb 1996 00:38:09 -0500
  6. Organization: Montclair State University
  7. Message-ID: <harmon.824447677@pegasus.montclair.edu>
  8. References: <4g009b$c2n@news.tuwien.ac.at>
  9. NNTP-Posting-Host: pegasus.montclair.edu
  10. X-Newsreader: NN version 6.5.0 #68 (NOV)
  11.  
  12. sor@rs6.iaee.tuwien.ac.at (Evgeni Sorokin) writes:
  13. >Given a float (double, to be exact) how do I 
  14.  
  15. >1) round it to nearest integer (forget 0.5 problem for the moment) and
  16. >2) truncate it to the integer?
  17.  
  18.    #2 first, to truncate any fractional component (it will still be of type
  19. double, however), use floor() on positive numbers and ceil() on negative
  20. numbers.  They are both in the standard <math.h>.  The answer for #1 involves
  21. adding 0.5 to the value, and then applying #2.
  22.  
  23. >          If typecasting is supposed to do the trick, then how do I
  24. >distinguish cases 1) and 2)?
  25.  
  26.    It is important to note that a C typecast only tells the compiler to treat
  27. some form of data as another form of data.  No change is made to the data.
  28. The binary representation of a double floating point value is very different
  29. from that of an integer, and just telling the compiler to treat it as an int
  30. will not solve your problem (for example, 7 != (int)'7').
  31.  
  32. unsigned int real2int( double real )
  33. {
  34.    unsigned int whole = 0;
  35.    unsigned int pow = 10000;        
  36.  
  37.    if (real > 65535.0) {
  38.       fputs(stderr, "real value too large in real2int().\n");
  39.       exit( 1 );
  40.    }
  41.    real = floor(real);
  42.    while ( pow > 0 ) 
  43.       if (real > (pow * 1.0)) {
  44.          real -= (pow * 1.0);
  45.          whole += pow;
  46.       } else pow /= 10;
  47.  
  48.    return( whole );
  49. }
  50.  
  51.    This little routine is more or less what you're looking for.  It makes
  52. several assumptions in that real must be positive, less than what a 16-bit
  53. unsigned int can hold (the extension to a long is straightforward), but you
  54. should find it workable.
  55.                                                           -- Stone
  56. --
  57. # Derek Harmon (aka Stonelight)    harmon@pegasus.montclair.edu
  58. # - Computer Science Undergrad, Montclair State University, NJ
  59. # - My views are my own, nobody else is this creative.  3;)>
  60. ... Sure I can program in Pascal, what's it Wirth to ya?
  61.